<template>
	<view class="container">
		<uni-forms ref="form" :rules="{}">
			<uni-forms-item label="电话:" name="">
				<uni-easyinput v-model="user.telephone" placeholder="请输入你的电话号码" />
			</uni-forms-item>
			<uni-forms-item label="密码:" name="">
				<uni-easyinput v-model="user.password" placeholder="请输入密码" />
			</uni-forms-item>
			<uni-forms-item label="密码:" name="">
				<uni-easyinput v-model="user.confirmPassword" placeholder="请再次输入密码" />
			</uni-forms-item>
			<uni-forms-item label="" name="">
				<button type="primary" @click="register">注册</button>
			</uni-forms-item>
		</uni-forms>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				user: {
					name: "",
					password: '',
					confirmPassword: '',
					telephone: '',
				}
			}
		},
		methods: {
			register() {
				// 表单验证
				this.$refs.form.validate().then(res => {
					if (!res) {
						uni.showToast({
							title: '请完整填写表单信息',
							icon: 'none'
						});
						return;
					}

					// 密码一致性校验
					if (this.user.password !== this.user.confirmPassword) {
						uni.showToast({
							title: '两次输入的密码不一致',
							icon: 'none'
						});
						return;
					}

					// 调用注册接口
					uni.request({
						url: 'http://localhost:8090/freshmenapp/user/register',
						method: 'POST',
						data: this.user,
						success: (res) => {
							const data = res.data;
							if (data.code !== 0) {
								uni.showModal({
									title: '提示',
									content: data.msg || '请稍后重试',
									showCancel: false
								});
								return;
							} else {
								uni.showToast({
									title: '注册成功'
								});
							}



							// 清空表单
							Object.assign(this.$data, this.$options.data());

							// 注册成功后跳转到登录页
							uni.navigateTo({
								url: '/pages/login/login'
							});
						},
						fail: (err) => {
							console.error(err);
							uni.showModal({
								title: '注册失败',
								content: '请求异常，请稍后重试',
								showCancel: false
							});
						}
					});
				})
			}
		}
	}
</script>

<style lang="scss">
	.container {
		padding: 20rpx;
	}

	.uni-forms-item {
		margin-bottom: 30rpx;

		&__label {
			font-size: 32rpx;
			width: 200rpx;
		}
	}

	.uni-input-input,
	.uni-input-placeholder {
		font-size: 28rpx;
	}

	uni-button {
		margin-top: 50rpx;
		font-size: 32rpx;
	}
</style>